var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var commentRouter = require('./routes/comment');
var vueRouter = require('./routes/vue');
var apiRouter = require('./routes/api');
var reactRouter = require('./routes/react');

var cors = require("cors")
require("./utils/connect")   // 链接数据库 
var app = express();
var session = require("express-session");

// view engine setup
app.set('views', path.join(__dirname, 'views')); //将views设置成根目录，以后目录都不需要写入views
app.set('view engine', 'ejs');

app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));  //处理express获取post请求  req.body获取不到数据报错缺少app.use(express.json());和当前代码加上即可+
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


// 中间件有先后顺序之分  
app.use(session({
  name: "AppTest",
  cookie: { maxAge: 1000 * 60 * 60 },  // session 时长
  secret: "test",
  resave: false,
  saveUninitialized: true
}))

//设置路由中间件 避免路由命名冲突
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/comment', commentRouter);
app.use('/vue', vueRouter);
app.use('/api', apiRouter);
app.use('/react', reactRouter);


// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));             //next()进行下一个中间件
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
